package com.jane.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.jane.adapter.homepageadapter.HeaderHomePagerAdapter;
import com.jane.adapter.homepageadapter.HomePageDataAdapter;
import com.jane.bean.HomePageGridViewBean;
import com.jane.bean.JsonData;
import com.jane.config.NetConfig;
import com.jane.definedview.GridViewWithHeaderAndFooter;
import com.jane.gzzb.GengDuoActivity;
import com.jane.gzzb.HomePageLiveActivity;
import com.jane.gzzb.PlayActivity;
import com.jane.gzzb.R;
import com.jane.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomePageFragment extends Fragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener {
    //声明
    private static final String TAG = HomePageFragment.class.getSimpleName();
    private View mView;
    private View mHeaderView;
    private ImageView mSearch;
    private TextView mGengduo;
    private GridViewWithHeaderAndFooter mHeaderGrid;
    private GridViewWithHeaderAndFooter mListView;
    private SwipeRefreshLayout mRefresh;
    private HomePageDataAdapter mAdapter;
    private HeaderHomePagerAdapter mHeaderAdapter;
    private int mPageIndex = 0;
    private List<HomePageGridViewBean> mData;
    private List<HomePageGridViewBean> mHeaderData;
    private String path;


    public HomePageFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_home_page, null);
        mHeaderView = inflater.inflate(R.layout.header_homepage, null);
        initView();
        mListView.addHeaderView(mHeaderView);//添加头布局
        initData();
        initListener();
        return mView;
    }

    private void initListener() {
        mSearch.setOnClickListener(this);
        mRefresh.setOnRefreshListener(this);
        mGengduo.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        mHeaderGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String sourcename = mHeaderData.get(position).getSourcename();
                int roomid = mHeaderData.get(position).getRoomid();
                String url = mHeaderData.get(position).getUrl();
                String commentator = mHeaderData.get(position).getCommentator();
                playWhich(sourcename, roomid + "", url, commentator);//页面跳转
            }
        });
    }

    private void initData() {
        mData = new ArrayList<>();
        mAdapter = new HomePageDataAdapter(getActivity(), mData);
        mListView.setAdapter(mAdapter);
        mHeaderData = new ArrayList<>();
        mHeaderAdapter = new HeaderHomePagerAdapter(getActivity(), mHeaderData);
        mHeaderGrid.setAdapter(mHeaderAdapter);

        //地址
        path = NetConfig.HOMEPAGE_URL;
        String jsonString = Utils.getJsonString(path);
        if (!TextUtils.isEmpty(jsonString)) {
            parserData(jsonString);//解析数据
        } else {
            //判断是否有网
            if (!Utils.isNetwork(getActivity())) {
                return;
            }
            //网络加载数据
            networkData();
        }
    }

    private void networkData() {
        x.http().get(new RequestParams(path), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (mPageIndex == 0) {//保存一份数据
                    JsonData jsonData = new JsonData();
                    jsonData.setPath(path);
                    jsonData.setJsonString(result);
                    Utils.saveJsonString(jsonData);
                }
                mRefresh.setRefreshing(false);//通知已刷新完成
                if (!TextUtils.isEmpty(result)) {
                    parserData(result);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mRefresh.setRefreshing(false);//通知已刷新完成
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void parserData(String result) {
        try {
            JSONObject obj0 = new JSONObject(result);
            //底部数据的解析
            JSONObject obj1 = obj0.getJSONObject("hot_live");
            JSONArray array0 = obj1.getJSONArray("data_list");
            JSONObject obj2 = array0.getJSONObject(0);
            JSONArray arry1 = obj2.getJSONArray("myArrayList");
            List<HomePageGridViewBean> lists = new ArrayList();
            for (int i = 0; i < arry1.length(); i++) {
                JSONObject obj3 = arry1.getJSONObject(i);
                JSONObject obj4 = obj3.getJSONObject("map");
                HomePageGridViewBean data = new HomePageGridViewBean();
                data.setSourcename(obj4.optString("sourcename"));
                data.setTitle(obj4.optString("title"));
                data.setRoomid(obj4.optInt("roomid"));
                data.setViewers(obj4.optInt("viewers"));
                data.setRawcoverimage(obj4.optString("rawcoverimage"));
                data.setName(obj4.optString("name"));
                data.setCommentator(obj4.optString("commentator"));
                data.setUrl(obj4.optString("url"));
                lists.add(data);
            }
            mData.addAll(lists);
            mAdapter.notifyDataSetChanged();

            //头部数据的解析
            JSONObject hobj1 = obj0.getJSONObject("con_live");
            JSONArray harray0 = hobj1.getJSONArray("data_list");
            JSONObject hobj2 = harray0.getJSONObject(0);
            JSONArray harry1 = hobj2.getJSONArray("myArrayList");
            List<HomePageGridViewBean> hlists = new ArrayList();
            for (int i = 0; i < harry1.length(); i++) {
                JSONObject hobj3 = harry1.getJSONObject(i);
                JSONObject hobj4 = hobj3.getJSONObject("map");
                HomePageGridViewBean hdata = new HomePageGridViewBean();
                hdata.setRawcommentatorimage(hobj4.optString("rawcommentatorimage"));
                hdata.setTitle(hobj4.optString("title"));
                hdata.setViewers(hobj4.optInt("viewers"));
                hdata.setInfotype(hobj4.optString("infotype"));
                hdata.setName(hobj4.optString("name"));
                hdata.setRoomid(hobj4.optInt("roomid"));
                hdata.setSourcename(hobj4.optString("sourcename"));
                hdata.setRawcoverimage(hobj4.optString("rawcoverimage"));
                hdata.setCommentator(hobj4.optString("commentator"));
                hdata.setUrl(hobj4.optString("url"));
                hlists.add(hdata);
            }
            mHeaderData.addAll(hlists);
//            Log.e(TAG, "parserData:---------- "+mHeaderData.size() );
            mHeaderAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        mListView = (GridViewWithHeaderAndFooter) mView.findViewById(R.id.fragment_home_page_gridview);
        mSearch = (ImageView) mView.findViewById(R.id.fragment_home_page_search);
        mRefresh = (SwipeRefreshLayout) mView.findViewById(R.id.fragment_home_page_refresh);
        mGengduo = (TextView) mHeaderView.findViewById(R.id.hearer_homepage_gengduo);
        mHeaderGrid = (GridViewWithHeaderAndFooter) mHeaderView.findViewById(R.id.hearer_homepage_gridview);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_home_page_search://查询

                break;
            case R.id.hearer_homepage_gengduo://更多
                Intent intent = new Intent(getActivity(), GengDuoActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onRefresh() {
        mData.clear();
        mHeaderData.clear();
        networkData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String sourcename = mData.get(position).getSourcename();
        int roomid = mData.get(position).getRoomid();
        String url = mData.get(position).getUrl();
        String commentator = mData.get(position).getCommentator();
        playWhich(sourcename, roomid + "", url, commentator);//页面跳转
    }

    private void playWhich(String sourcename, String roomid, String url, String commentator) {
        //共12平台
        if (sourcename != null && roomid != null && url != null && commentator != null) {
            switch (sourcename) {
                case "熊猫":
                case "全民":
                case "斗鱼":
                    Intent intent = new Intent(getActivity(), PlayActivity.class);
                    intent.putExtra("sourcename", sourcename);
                    intent.putExtra("roomid", roomid);
                    startActivity(intent);
                    break;
                default:
                    Intent intent1 = new Intent(getActivity(), HomePageLiveActivity.class);
                    intent1.putExtra("url", url);
                    intent1.putExtra("commentator", commentator);
                    startActivity(intent1);
                    break;
            }
        }
    }

}
